

const router = require('koa-router')();
const util = require("../common/utils")
const { sequelize } = require('../common/dbs')
var qiniu = require('qiniu');

var request = require('request')
const cheerio = require('cheerio')

// typeinfo
router.get('/getQiNiuToken', async (ctx) => {
    try {
        var accessKey = 'XR714N7-gF03mCTw8GGdtBcJlo5mhgTlDCKSjo5d';
        var secretKey = 'BtX-wq_jQM2XGuo0w9vI3dM6lDpB53SVuRcTOCVL';
        var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
        var options = {
            scope: 'itliuyang',
            expires: 7200,
        };
        var putPolicy = new qiniu.rs.PutPolicy(options);
        var uploadToken = putPolicy.uploadToken(mac);
        ctx.body = util.resultSuccess({ data: uploadToken });
    } catch (error) {
        console.log(error);
        ctx.body = util.resultError({ data: error });

    }

})


var fs = require("fs");
const path = require('path');
const mime = require('mime-types'); //需npm安装

const fileModel = require("../models/file")
const fileinfo = fileModel(sequelize);
// 默认图地址
const defaultImg = '../public/default.jpg'
// 路径前缀
const pathQz = '../public/upload/'


router.post('/upload', async (ctx, next) => {
    try {
        var files = ctx.request.files.file;
        // 单个文件变成数组
        if (files.length === undefined) {
            files = [files]
        }
        // 需要添加到数据库的数据
        var fileDatas = []
        // 获取目录文件夹名字
        var uloadDirName = getUploadDirName();
        // 遍历文件
        for (var i = 0; i < files.length; i++) {
            const f1 = files[i];
            // 随机文件名
            var fileName = getuuid();
            // 获取文件后缀
            let ext = f1.name.split('.');
            var fileNamePath = getuuid() + "." + ext[ext.length - 1];
            // 添加数据库的数据
            fileDatas.push({
                filename: `${uloadDirName}/${fileNamePath}`,
                fileid: fileName
            });
            // 读取文件流
            fileReader = fs.createReadStream(f1.path);
            // 最终要保存到的文件夹目录
            const dir = path.join(__dirname, `${pathQz}${uloadDirName}`);
            // 检查文件夹是否存在如果不存在则新建文件夹
            checkDirExist(dir);
            // 组装路径
            fileResource = dir + `/${fileNamePath}`;
            //   创建可写流
            writeStream = fs.createWriteStream(fileResource);
            // 可读流通过管道写入可写流
            fileReader.pipe(writeStream);
        }
        // 批量添加
        var requestData = await fileinfo.bulkCreate(fileDatas)
        if (requestData.length == files.length) {
            // 得到id拼接数组
            var resultIds = requestData.map(item => {
                return item.fileid
            })
            ctx.body = util.resultSuccess({
                message: '上传成功', data: {
                    fileid: resultIds.toString()
                }
            });
        } else {
            ctx.body = util.resultSuccess({ code: 0, message: '上传失败', data: null });
        }
    } catch (error) {
        console.log(error)
        ctx.body = util.resultError({ code: 0, message: '上传失败', data: error });
    }

});
// 读取文件
router.get('/file', async (ctx, next) => {
    var filePath = null;
    var file = null;
    try {
        var reqQuery = ctx.request.query;
        // 查询数据库
        var cardData = await fileinfo.findOne(
            {
                attributes: {   // exclude排除
                    exclude: ['id', 'devaredAt'],
                },
                where: {
                    // 条件
                    fileid: reqQuery.fileid
                }
            }
        );
        if (cardData) {
            const name = cardData.filename;
            // 拼接路径
            const pathName = `${pathQz}${name}`;
            filePath = path.join(__dirname, pathName); //完整图片地址
            showFile(ctx, filePath);
        } else {
            ctx.body = util.resultError({ code: 0, message: err.message, data: null });
        }
    } catch (error) {
        //如果服务器不存在请求的图片，返回默认图片
        filePath = path.join(__dirname, defaultImg); //默认图片地址
        showFile(ctx, filePath);
    }

});

var http = (url) => {
    return new Promise((resolve, reject) => {
        request({
            url: url,
            method: 'GET'
        }, (err, response, body) => {
            if (err) {
                console.log(err)
            }
            resolve(body)
        })
    })
}
// 解析html
router.post('/uploadHtml', async (ctx, next) => {
    try {
        var files = ctx.request.files.file;
         // 获取目录文件夹名字
         var uloadDirName = getUploadDirName();
        const f1 = files;
        // 随机文件名
        var fileName = getuuid();
        // 获取文件后缀
        let ext = f1.name.split('.');
        
        var fileNamePath = getuuid() + "." + ext[ext.length - 1];
        
        // 读取文件流
        fileReader = fs.createReadStream(f1.path);
        // console.log("==>",fileNamePath)
        // 最终要保存到的文件夹目录
        const dir = path.join(__dirname, `${pathQz}/html`);
        // console.log(dir)
        // 检查文件夹是否存在如果不存在则新建文件夹
        checkDirExist(dir);
        // 组装路径
        fileResource = dir + `\\${fileNamePath}`;
        //   创建可写流
        writeStream = fs.createWriteStream(fileResource);
        // 可读流通过管道写入可写流
        fileReader.pipe(writeStream);
        console.log(fileResource)
        
        fs.readFile(fileResource,'utf-8', (err, data) => {
            console.log(data.split("<DT><A"))
            ctx.body = util.resultError({ code: 0, message: '22', data: data.split("<DT><A") });
        })
         console.log('111')
        // ctx.body = util.resultError({ code: 0, message: '22', data: fileResource });
    } catch (error) {
        ctx.body = util.resultError({ code: 0, message: '上传失败', data: error });
    }

});


// 显示图片
function showFile(ctx, filePath) {
    try {
        file = fs.readFileSync(filePath); //读取文件
    } catch (error) {
        //如果服务器不存在请求的图片，返回默认图片
        filePath = path.join(__dirname, defaultImg); //默认图片地址
        file = fs.readFileSync(filePath); //读取文件	    
    }
    var mimeType = mime.lookup(filePath); //读取图片文件类型
    ctx.set('content-type', mimeType); //设置返回类型
    ctx.body = file; //返回图片

}
//检查文件夹是否存在
function checkDirExist(p) {
    if (!fs.existsSync(p)) {
        fs.mkdirSync(p);
    }
}
// 文件夹名字
function getUploadDirName() {
    const date = new Date();
    var month = Number.parseInt(date.getMonth()) + 1;
    month = month.toString().length > 1 ? month : `0${month}`;
    const dir = `${date.getFullYear()}${month}${date.getDate()}`;
    return dir;
}

// 随机id
function getuuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    var uuid = s.join("");
    return uuid;
}
module.exports = router.routes();